const { promises } = require("dns");
var fs = require("fs");
const { resolve } = require("path");
// 获取文件
function getFileData(url) {
  return new Promise((resolve, reject) => {
    fs.readFile(url, (err, data) => {
      // console.log(err.code,999);
      if (err) {
        if (err.code === "ENOENT") {
          resolve({});
          return;
        }
      }
      if (data.toString().length === 0) {
        resolve({});
      } else {
        resolve(JSON.parse(data.toString()));
      }
    });
  });
}

// 写入文件 追加模式
function setFileData(url, data) {
  return new Promise((resolve, reject) => {
    fs.open(url, "w", (err, fd) => {
      // console.log(err,111);
      if (err) {
        reject(err);
      }
      fs.write(fd, JSON.stringify(data), (err) => {
        if (err) {
          reject(err);
        }
        fs.close(fd, (err) => {
          if (err) {
            reject(err);
          }
          resolve("写入成功");
        });
      });
    });
  });
}
module.exports = {
  getFileData,
  setFileData,
};
